import Vue from 'vue';
import qs from 'qs';
import * as types from './mutation-type.js';
import httpsRequest from '@/assets/httpsRequest'

export default {
  async getCommentsList({ commit, state }, { payload }) {
    const res = await httpsRequest({
      url: `getcomments/${payload.id}`,
      params: {
        pageindex: payload.page
      },
    });
    const { status, data = {} } = res;
    const { message = [] } = data;
    if (status === 200) {
      if (!message.length) {
        Vue.prototype.$toast('评论数据已加载完!');
        return false;
      }
      // 加载首页的时候数组置空
      const list = payload.page === 1 ? [] : state.commentsList;
      commit({
        type: types.SET_COMMENTS,
        payload: {
          // state之前的状态
          commentsList: list.concat(message),
        },
      });
    }
  },
  async submitComment({ dispatch }, { payload }) {
    const res = await httpsRequest({
      method: 'post',
      url: `postcomment/${payload.id}`,
      data: qs.stringify({
        content: payload.introduction,
      }),
    });
    const { status } = res;
    if (status === 200) {
      Vue.prototype.$toast({
        message: '提交成功',
        iconClass: 'icon icon-success',
      });
      dispatch({
        type: 'getCommentsList',
        payload: {
          id: payload.id,
          page: 1,
        },
      });
    }
  },
};
